package com.fenqing.utils;

import cn.hutool.core.lang.TypeReference;
import cn.hutool.json.JSONUtil;
import com.fenqing.bean.TreeNode;

import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

/**
 * @author fenqing
 */
public class StringToTreeNodeEncoder implements Encoder<String, TreeNode>{
    @Override
    public TreeNode encoder(String input) {
        input = input.trim();
        List<Integer> lists = JSONUtil.toBean(input, new TypeReference<List<Integer>>() {
        }, true);
        Queue<TreeNode> queue = new LinkedList<>();
        Integer integer = lists.get(0);
        TreeNode treeNode = new TreeNode(integer);
        queue.add(treeNode);
        int i = 1;
        while (!queue.isEmpty() && i < lists.size()) {
            TreeNode poll = queue.poll();
            if (i < lists.size()) {
                Integer integer1 = lists.get(i++);
                if (integer1 != null) {
                    poll.left = new TreeNode(integer1);
                    queue.offer(poll.left);
                }
            }
            if (i < lists.size()) {
                Integer integer1 = lists.get(i++);
                if (integer1 != null) {
                    poll.right = new TreeNode(integer1);
                    queue.offer(poll.right);
                }
            }
        }
        return treeNode;
    }
}
